package com.dzl.util;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MapUtil {
	
	/**
	 * 实体对象转成Map
     * @param obj 实体对象
     * @return
     */
	public static Map<String, Object> object2Map(Object obj){
		Map<String, Object> map = new HashMap<>();
		Class clazz = obj.getClass();
		Field[] fields = clazz.getDeclaredFields();
		try {
			for (Field field : fields) {
				field.setAccessible(true);
				map.put(field.getName(), field.get(obj));
			}
		} catch (Exception e) {
			 e.printStackTrace();
		}
		return map;
	}

	public static Object map2Object(Map<String, Object> map, Class<?> clazz) {
		 if (map == null) {
	            return null;
	     }
		 Object obj = null;
		 try {
			 obj = clazz.newInstance();
			 Field[] fields = obj.getClass().getDeclaredFields();
			 for (Field field : fields) {
				 int mod = field.getModifiers();
				 if (Modifier.isStatic(mod) || Modifier.isFinal(mod)) {
	                continue;
	             }
				 field.setAccessible(true);
				 field.set(obj, map.get(field.getName()));
			 }
		} catch (Exception e) {
			 e.printStackTrace();
		}
		 return obj;
	}

	public static <T> List<Map<String, Object>> convertListBean2ListMap(List<T> beanList, Class<T> T){
		List<Map<String, Object>> mapList = new ArrayList<>();
		try {
			if(!EmptyUtils.isEmpty(beanList)) {
				for (int i = 0, n = beanList.size(); i < n; i++) {
					Object bean = beanList.get(i);
					Map<String, Object> map = object2Map(bean);
					mapList.add(map);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return mapList;
	}
}
